/*
 * @Author: LiZhiWei
 * @Date: 2025-07-15 10:20:21
 * @LastEditors: wjc
 * @LastEditTime: 2025-10-29 17:53:31
 * @Description: 统一的编辑功能Hook，支持弹窗编辑和嵌入式编辑
 */
import { useRoute } from 'vue-router'

import { api, Http } from '#/api'
import Validation from '#/utils/validation'
import { ElMessage } from 'element-plus'

export function useEditor(
  options: {
    entity?: string
    formSize?: 'large' | 'mini' | 'normal' | string
    message?: string
    mode?: 'embed' | BaseFormMode
  } = {
    mode: 'dialog',
    formSize: 'normal',
    entity: '',
    message: '编辑成功',
  }
) {
  const { entity = '', message, formSize } = options
  const route = useRoute()
  // 通用状态
  const loading = ref(false)
  const formLoading = ref(false)
  const modelId = route.params.id

  // 编辑对话框或抽屉
  const editDialog = ref({
    visible: false,
    entity,
    size: formSize,
    id: 0 as number | string,
    index: 0,
  })

  // 通用表单
  const editFormer = ref({
    fields: [],
    data: {},
    validate: new Validation(),
  })

  // 弹窗编辑
  const showEditor = (id: number | string, index = 0) => {
    editDialog.value.id = id
    editDialog.value.index = index
    editDialog.value.visible = true
  }

  const edit = (url: string, params: any) => {
    if (loading.value) return Promise.reject(new Error('操作进行中'))
    loading.value = true

    return Http.Get(url, { params })
      .then((res: any) => {
        return res
      })
      .finally(() => {
        loading.value = false
      })
  }

  const afterGetEdited = (res: any, onEdited?: (res: any) => void) => {
    editFormer.value.fields = res.form_widgets
    editFormer.value.data = res.data
    onEdited && onEdited(res)
  }

  // 获取表单配置
  const getEditForm = (onSucceed?: (res: any) => void) => {
    return edit(api[entity].edit(modelId), {}).then((res) => {
      afterGetEdited(res, onSucceed)
    })
  }

  const getEditFormWithId = (id: number | string, onSucceed?: (res: any) => void) => {
    return edit(api[entity].edit(id), {}).then((res) => {
      afterGetEdited(res, onSucceed)
    })
  }

  const getEditFormWith = (url: RequestUrl, onSucceed?: (res: any) => void) => {
    return edit(url.edit as string, url.params).then((res) => {
      afterGetEdited(res, onSucceed)
    })
  }

  const update = (url: string, data: any) => {
    if (formLoading.value) return Promise.reject(new Error('操作进行中'))
    formLoading.value = true

    return Http.Put(url, data)
      .then((res: any) => {
        ElMessage({ type: 'success', message: message ?? '编辑成功' })
        editFormer.value.validate.clean()
        return res
      })
      .catch((error) => {
        editFormer.value.validate.setMessages(error?.response?.data?.errors)
        formLoading.value = false
        throw error
      })
      .finally(() => {
        formLoading.value = false
      })
  }

  const afterUpdated = (res: any, onUpdated?: (res: any) => void) => {
    onUpdated && onUpdated(res)
  }

  const handleUpdate = (form: object, id: number | string, onConfirmed?: (res: any) => void) => {
    return update(api[entity].update(id), form).then((res) => {
      afterUpdated(res, onConfirmed)
    })
  }

  const handleUpdateWith = (url: RequestUrl, onConfirmed?: (res: any) => void) => {
    return update(url.update as string, url.params).then((res) => {
      afterUpdated(res, onConfirmed)
    })
  }

  const resetEditor = () => {
    formLoading.value = false
    loading.value = false
    editFormer.value?.validate.clean()
  }

  const getReturnRoute = (routeName?: string) => {
    return routeName || `${entity}Index`
  }

  return {
    loading,
    formLoading,
    modelId,
    editDialog,
    editFormer,
    showEditor,
    resetEditor,
    getEditForm,
    getEditFormWithId,
    getEditFormWith,
    handleUpdate,
    handleUpdateWith,
    getReturnRoute,
  }
}
